package com.xxq.semester.component;

import com.xxq.semester.service.utils.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RateLimitComponent {

    @Autowired
    private RedisService redisService;

    /**
     * 检查是否超过限流
     *
     * @param key 限流key
     * @param maxCount 最大请求数
     * @param window 时间窗口
     * @param unit 时间单位
     * @return true表示通过，false表示被限流
     */
    public boolean tryAcquire(String key, int maxCount, long window, TimeUnit unit) {
        return redisService.tryAcquire(key, maxCount, window, unit);
    }

    /**
     * 登录限流
     *
     * @param ip IP地址
     * @return 是否通过限流
     */
    public boolean loginRateLimit(String ip) {
        return tryAcquire("login:" + ip, 5, 15, TimeUnit.MINUTES);
    }

    /**
     * 注册限流
     *
     * @param ip IP地址
     * @return 是否通过限流
     */
    public boolean registerRateLimit(String ip) {
        return tryAcquire("register:" + ip, 3, 60, TimeUnit.MINUTES);
    }

    /**
     * API请求限流
     *
     * @param ip IP地址
     * @return 是否通过限流
     */
    public boolean apiRateLimit(String ip) {
        return tryAcquire("api:" + ip, 100, 1, TimeUnit.MINUTES);
    }

    /**
     * 获取用户IP
     *
     * @param request HttpServletRequest
     * @return IP地址
     */
    public String getClientIp(jakarta.servlet.http.HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
